﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XmlTypes;
namespace CxExtension
{
	public static class StringExtension
	{
		/// <summary>
		/// 数组分隔符： ','
		/// </summary>
		private const Char LIST_SPRITER = ',';
		/// <summary>
		/// 将列表字符串转换为字符串的列表对象。
		/// </summary>
		/// <param name="strList">列表字符串</param>
		/// <param name="listSpriter">数组分隔符</param>
		/// <returns>列表对象</returns>
		public static List<String> ParseList(this String strList,Char listSpriter = LIST_SPRITER)
		{
			var result = new List<String>();
			if(String.IsNullOrEmpty(strList))
				return result;

			var trimString = strList.Trim();
			if(String.IsNullOrEmpty(strList))
			{
				return result;
			}
			var detials = trimString.Split(listSpriter);//.Substring(1, trimString.Length - 2)
			foreach(var item in detials)
			{
				if(!String.IsNullOrEmpty(item))
					result.Add(item.Trim());
			}

			return result;
		}
		public static object ParseValue(this string self,Type type)
		{
			if(type == null)
				return null;
			if(type == typeof(string))
				return self;
			else if(type.IsGenericType)
			{
				Type gnType = type.GetGenericTypeDefinition();//取得模板类型
				var result = type.GetConstructor(Type.EmptyTypes).Invoke(null);
				if(gnType == typeof(List<>))
				{
					Type argumentsType = type.GetGenericArguments()[0];//取得 List<T>中 T的类型
					var list = self.ParseList();
					foreach(var item in list)
					{
						var v = item.ParseValue(argumentsType);
						type.GetMethod("Add").Invoke(result,new object[] { v });
					}
				}
				return result;
			}
			else
			{
				var parse = type.ParseMethod();
				if(parse != null)
				{
					object[] param = { self };
					var v = parse.Invoke(null,param);
					return v;
				}
			}
			return null;
		}
		public static T ParseValue<T>(this string self)
		{
			Type type = typeof(T);
			object value = self.ParseValue(type);
			return (T)value;
		}
	}
}
